package com.zhanghe.study.mybatis;

import com.zhanghe.study.mybatis.mapper.UserMapper;
import com.zhanghe.study.mybatis.model.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.InputStream;
import java.util.Properties;

/**
 * @author zh
 * @date 2021/1/11 17:21
 */
public class Main {

    public static SqlSessionFactory createFactory(){
        // 获取到mybatis-config.xml配置文件，进而构建SqlSessionFactory
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
        Properties props = new Properties();
        props.put("jdbc.password","123456");
        return new SqlSessionFactoryBuilder().build(is,props);
    }

    public static SqlSession getCurrentSession(){
        SqlSessionFactory factory = createFactory();
        return factory.openSession(true);
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUser(8);
        System.out.println(user);
    }

}
